package com.xuan.chatroom.config;

import com.xuan.chatroom.controller.TestWebSocket;
import com.xuan.chatroom.controller.WebSocketAPI;
import com.xuan.chatroom.interceptor.SaveTokenInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    @Autowired
    private WebSocketAPI webSocketAPI;
    @Autowired
    private SaveTokenInterceptor saveTokenInterceptor;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        // 通过这个方法,可以把创建好的 handler类 给注册到具体的路径上
        // 如果此时浏览器, websocket的请求路径是"/test"时,就会调用到 TestWebSocket类中的方法
        registry.addHandler(webSocketAPI, "/WebSocketMessage")
                // 通过注册这个特殊的拦截器,就可以把 HttpSession 中添加的 Attribute属性 往WebSocketSession中添加一份
                .addInterceptors(saveTokenInterceptor)
                .setAllowedOrigins("*");
    }

}
